package cn.flashapp.queue;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

public class EncodingAndThreadLocalFilter implements Filter {
	private String encoding = "UTF-8";

	private static ThreadLocal<HttpServletRequest> requests = new ThreadLocal<HttpServletRequest>();
	private static ThreadLocal<HttpServletResponse> responses = new ThreadLocal<HttpServletResponse>();

	public static HttpServletRequest getRequest() {
		return (HttpServletRequest) requests.get();
	}
	
	public static HttpServletResponse getResponse() {
		return (HttpServletResponse) responses.get();
	}

	public static HttpSession getSession() {
		if (getRequest() != null) {
			return (HttpSession) getRequest().getSession();
		}
		return null;
	}

	public static HttpSession getSession(boolean create) {
		if (getRequest() != null) {
			return (HttpSession) getRequest().getSession(create);
		}
		return null;
	}

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request  = (HttpServletRequest) servletRequest;
		requests.set((HttpServletRequest) request);
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		responses.set((HttpServletResponse) response);
		servletRequest.setCharacterEncoding(encoding);
		servletResponse.setCharacterEncoding(encoding);
		
		filterChain.doFilter(servletRequest, servletResponse);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		String ec = arg0.getInitParameter("encoding");
		if ( !StringUtils.isBlank( ec ) ) 
			encoding = ec;
	}
}